<template>
  <div>
    <Row :gutter="20">
      <Col span="6">
        <Card dis-hover class="pandx">
          <p slot="title">
          </p>
          <Button type="primary" slot="extra" icon="md-create" @click="create(false)"
                  :disabled="!hasPermission('Pages.Administration.OrganizationUnits.Create')">新建根单位
          </Button>
          <Tree ref="tree" :data="treeData" :render="renderNode" @on-contextmenu="handleContextMenu">
            <template slot="contextMenu">
              <DropdownItem @click.native="create(true)" :disabled="!hasPermission('Pages.Administration.OrganizationUnits.Create')">新建下级单位</DropdownItem>
              <DropdownItem @click.native="update" :disabled="!hasPermission('Pages.Administration.OrganizationUnits.Update')">更新</DropdownItem>
              <DropdownItem @click.native="remove" :disabled="!hasPermission('Pages.Administration.OrganizationUnits.Delete')">删除</DropdownItem>
              <DropdownItem divided @click.native="display" :disabled="!hasPermission('Pages.Administration.OrganizationUnits.Browse')">查看代码</DropdownItem>
            </template>
          </Tree>
        </Card>
      </Col>
      <Col span="18">
        <Card dis-hover v-show="!ou.id">
          <div slot="title" style="margin-top:8px;">
            &nbsp;
          </div>
          请在左侧选择一个单位
        </Card>
        <Card dis-hover v-show="ou.id">
          <div slot="title" style="margin-top:8px;">
            <strong>{{ ou.displayName }}</strong> 下的成员
          </div>
          <Button type="success" slot="extra" icon="md-add" @click="add"  :disabled="!hasPermission('Pages.Administration.OrganizationUnits.AddUser')">添加成员
          </Button>
          <Table :loading="loading" :columns="columns" no-data-text="没有任何数据"
                 no-filtered-data-text="没有任何数据" border
                 :data="addedUsers" class="margin-top-10" @on-sort-change="sortChange" @on-filter-change="filterChange">
            <template slot-scope="{row}" slot="actions">
              <Button type="default" size="small" @click="removeUser(row)"
                      :disabled="!hasPermission('Pages.Administration.OrganizationUnits.RemoveUser')">
                <Icon type="md-close"></Icon>
              </Button>
            </template>
          </Table>
          <Page show-sizer show-total :total="addedCount" class="margin-top-10"
                @on-change="pageChange"
                @on-page-size-change="pageSizeChange" :page-size="addedPageSize"
                :current="addedCurrentPage"
                :page-size-opts="[5,10,15]">
          </Page>
        </Card>
      </Col>
    </Row>
    <o-u-modal v-model="ouModalShow" :modal-data="ouData" v-if="ouModalMount"
               @save-success="handleOUSaveSuccess"></o-u-modal>
    <user-modal v-model="userModalShow" :modal-data="userData" v-if="userModalMount"
                @save-success="handleUserSaveSuccess"></user-modal>

  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import OUModal from '@/views/administration/organization-unit/modal/o-u-modal.vue';
import PageRequest from '@/store/entities/page-request';
import Util from '@/lib/util';
import UserModal from '@/views/administration/organization-unit/modal/user-modal.vue';
import UserExpand from '@/components/expand/user-expand.vue';
import OU from '@/store/entities/administration/organization-unit/o-u';

class PageUserRequest extends PageRequest {
  id: number = 0;
  n: number = 0;
  gender: number[] = [];
  isActive: boolean[] = [];
}

@Component({
  components: {
    OUModal,
    UserModal,
    UserExpand,
  },
})
export default class OrganizationUnit extends AbpBase {
  name: string = 'OrganizationUnit';

  ouModalMount: boolean = false;
  ouModalShow: boolean = false;
  ouData: any = {};

  userModalMount: boolean = false;
  userModalShow: boolean = false;
  userData: any = {};

  pageUserRequest: PageUserRequest = new PageUserRequest();
  ou: OU = new OU();
  contextData: any = null;
  nodeKey: number = 0;

  columns = [
    {
      title: '操作',
      slot: 'actions',
      width: 70,
      align: 'center',
    },
    {
      type: 'expand',
      width: 30,
      render: (h: any, params: any) => {
        return h(UserExpand, {
          props: {
            row: params.row,
          },
        }, []);
      },
    },
    {
      title: '用户名',
      key: 'userName',
      align: 'center',
      width: 120,
      sortable: this.$config.sorting.administration.user,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
    {
      title: '姓名',
      key: 'name',
      align: 'center',
      width: 120,
      sortable: this.$config.sorting.administration.user,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
    {
      title: '性别',
      key: 'gender',
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.gender) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.info,
              type: 'pandx fa fa-mars',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.warning,
              type: 'pandx fa fa-venus',
            },
          }, []);
        }
      },
      width: 90,
      filters: [
        {
          label: '男',
          value: 1,
        }, {
          label: '女',
          value: 0,
        },
      ],
      filterRemote: (array) => {
        this.pageUserRequest.gender = array;
        this.getPage();
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
    {
      title: '角色',
      key: 'roles',
      align: 'center',
      minWidth: 180,
      render: (h: any, params: any) => {
        return h('span', {}, params.row.roles.map(el => el.roleName).join('，'));
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
    {
      title: '激活',
      key: 'isActive',
      align: 'center',
      width: 90,
      render: (h: any, params: any) => {
        if (params.row.isActive) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flash',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flash',
            },
          }, [])
        }
      },
      filters: [
        {
          label: '已激活',
          value: true,
        }, {
          label: '未激活',
          value: false,
        },
      ],
      filterRemote: (array) => {
        this.pageUserRequest.isActive = array;
        this.getPage()
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
    {
      title: '添加时间',
      key: 'addedTime',
      align: 'center',
      width: 180,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime((params.row.addedTime)));
      },
      sortable: this.$config.sorting.administration.user,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme:'dark',
    },
  ];




  get list() {
    return this.$store.state.ou.list;
  }

  get treeData() {
    return this.getTreeData(null);
  }

  get addedUsers() {
    return this.$store.state.ou.addedUsers;
  }


  get addedCount() {
    return this.$store.state.ou.addedCount;
  }


  get loading() {
    return this.$store.state.ou.loading;
  }


  get addedCurrentPage() {
    return this.$store.state.ou.addedCurrentPage;
  }


  get addedPageSize() {
    return this.$store.state.ou.addedPageSize;
  }




  handleContextMenu(data: any) {
    this.clickSpan(data);

    this.$set(data, 'selected', false);
    this.findNodeKey((this.$refs.tree as any).data, data);
    this.$nextTick(() => {
      (this.$refs.tree as any).$emit('on-selected', this.nodeKey);
    });
    this.contextData = data;
  }

  async removeUser(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要从单位 ' + this.ou.displayName + ' 中删除用户 ' + row.name + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'ou/removeUserFromOrganizationUnit',
          data: {
            userId: row.id,
            organizationUnitId: this.ou.id,
          },
        });
        await this.$store.dispatch({
          type: 'ou/getOrganizationUnits',
        });
        const data = {
          extra: this.ou,
        };
        await this.clickSpan(data);
        this.findNodeKey((this.$refs.tree as any).data, data);
        this.$nextTick(() => {
          (this.$refs.tree as any).$emit('on-selected', this.nodeKey);
        });
        this.$Message.success({
          background: true,
          content: '从单位 ' + this.ou.displayName + ' 中删除用户 ' + row.name + ' 成功',
          duration: this.$config.duration,
        });

      },
      onCancel: () => {
      },
    });
  }

  async handleUserSaveSuccess(status: boolean, ou: any) {
    if (status) {
      await this.$store.dispatch({
        type: 'ou/getOrganizationUnits',
      });
      const data = {
        extra: ou,
      };

      await this.clickSpan(data);
      this.findNodeKey((this.$refs.tree as any).data, data);
      this.$nextTick(() => {
        (this.$refs.tree as any).$emit('on-selected', this.nodeKey);
      });
    }
  }

  async add() {
    this.userData = {data: this.ou};
    this.userModalMount = true;
    this.$nextTick(() => {
      this.userModalShow = true;
    });
  }


  async pageChange(page: number) {
    this.$store.commit('ou/setAddedCurrentPage', page);
    await this.getPage();
  }


  async pageSizeChange(pageSize: number) {
    this.$store.commit('ou/setAddedPageSize', pageSize);
    await this.getPage();
  }

  async sortChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageUserRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  filterChange(column: any) {
  }

  async handleOUSaveSuccess(ou: any) {
    const data = {
      extra: ou,
    };
    await this.clickSpan(data);
    this.findNodeKey((this.$refs.tree as any).data, data);
    this.$nextTick(() => {
      (this.$refs.tree as any).$emit('on-selected', this.nodeKey);
    });
  }

  async create(tag: boolean) {
    if (tag) {
      this.ouData = {data: this.contextData, update: false}
    } else {
      this.ouData = {data: null, update: false}
    }
    this.ouModalMount = true;
    this.$nextTick(() => {
      this.ouModalShow = true;
    });
  }

  async update() {
    this.ouData = {data: this.contextData, update: true};
    this.ouModalMount = true;
    this.$nextTick(() => {
      this.ouModalShow = true;
    });
  }

  async remove() {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除单位 ' + this.contextData.extra.displayName + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'ou/deleteOrganizationUnit',
          data: this.contextData.extra,
        });
        this.$Message.success({
          background: true,
          content: '单位 ' + this.contextData.extra.displayName + ' 已删除成功',
          duration: this.$config.duration,
        });
        this.ou = new OU();
      },
      onCancel: () => {
      },
    });

  }

  display() {
    this.$Message.info({
      background: true,
      content: '单位 ' + this.contextData.extra.displayName + ' 的代码是 ' + this.contextData.extra.code,
      duration: this.$config.duration,
    });
  }


  async getPage() {
    this.pageUserRequest.maxResultCount = this.addedPageSize;
    this.pageUserRequest.skipCount = (this.addedCurrentPage - 1) * this.addedPageSize;
    this.pageUserRequest.id = this.ou.id;
    this.pageUserRequest.n = Math.random();
    await this.$store.dispatch({
      type: 'ou/obtainOrganizationUnitUsers',
      data: this.pageUserRequest,
    });
  }

  getTreeData(parentId: number) {
    let array: any[] = [];
    this.list.forEach((item) => {
      if (item.parentId === parentId) {
        let n: any = {};
        n.title = item.displayName + ' （' + item.memberCount + '）';
        n.expand = true;
        n.contextmenu = true;
        n.extra = item;
        n.render = (h, {root, node, data}) => {
          return this.renderNode(h, {root, node, data});
        };
        n.children = this.getTreeData(item.id);
        array.push(n);
      }
    });
    return array;
  }

  renderNode(h, {root, node, data}) {
    return h('span', {
      style: {
        display: 'inline-block',
      },
      on: {
        click: async () => {
          await this.clickSpan(data);
        },
      },
    }, [
      h('Icon', {
        props: {
          type: 'pandx fa fa-building-o',
        },
        style: {
          marginRight: '8px',
        },
      }, []),
      h('span', {}, data.title),
    ]);
  }

  findNodeKey(array: any[], data: any) {
    array.forEach((item) => {
      if (item.extra.id === data.extra.id) {
        this.nodeKey = item.nodeKey;
      } else {
        if (item.children.length > 0) {
          this.findNodeKey(item.children, data);
        }
      }
    });
  }

  async clickSpan(data: any) {
    this.pageUserRequest.sorting = '';
    this.pageUserRequest.gender = [];
    this.pageUserRequest.isActive = [];
    this.ou = data.extra;
    await this.getPage();
  }



  async created() {
    await this.$store.dispatch({
      type: 'ou/getOrganizationUnits',
    });
  }

}
</script>

<style lang="less" scoped>
.pandx::v-deep .ivu-card-body{
  height:calc(100vh - 195px);
}
</style>
